package com.guan.ojcommonsecurity.inteceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.guan.common.core.constants.Constants;
import com.guan.common.core.constants.HttpConstants;
import com.guan.common.core.utils.ThreadLocalUtil;
import com.guan.ojcommonsecurity.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;



@Component
public class TokenInterceptor  implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret; // 从哪个服务的配置文件中读取，取决于bean对象交给了哪个服务的spring容器进行管理

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = getToken(request); // 从请求头中获取token
        if (StrUtil.isEmpty(token)) {
            return true;
        }
        Long userId = tokenService.getUserId(token, secret);
        String userKey = tokenService.getUserKey(token, secret);
        ThreadLocalUtil.set(Constants.TTL_KEY_USER_KEY, userKey);
        ThreadLocalUtil.set(Constants.TTL_KEY_USER_ID, userId);
        //System.out.println("preHandle:\n userid:" + ThreadLocalUtil.get(Constants.TTL_KEY_USER_ID, Long.class) + "\n userKey:" + ThreadLocalUtil.get(Constants.TTL_KEY_USER_KEY, String.class));
        tokenService.extendToken(token, secret);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        ThreadLocalUtil.remove();
    }

    private String getToken(HttpServletRequest request){
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if(StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token = token.replaceFirst(HttpConstants.PREFIX, "");
        }
        return token;
    }
}
